package com.bos.service.imp;

import com.bos.dao.IDecideZoneDao;
import com.bos.dao.INoticeBillDao;
import com.bos.dao.IWorkBillDao;
import com.bos.dao.IWorkOrderManagerDao;
import com.bos.domain.*;
import com.bos.service.NoticeBillService;
import com.bos.utils.BOSUtil;
import com.crm.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

/**
 * @author Administrator
 */

@Service
@Transactional
public class NoticeBillServicImp implements NoticeBillService {

    @Autowired
    private INoticeBillDao noticeBillDao;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private IWorkBillDao workBillDao;

    @Autowired
    private IDecideZoneDao decideZoneDao;

    @Override
    public void save(Noticebill noticebill) {
        User user = BOSUtil.getUser();

        //设置操作该单的用户（客服/相关工作人员）
        noticebill.setUser(user);

        String pickaddress = noticebill.getPickaddress();
        String decidedZoneID = customerService.findDecidedZoneIDbyAddress(pickaddress);
        if (decidedZoneID != null) {
            //查询到定区id可以完成自动分单
            noticebill.setOrdertype(Noticebill.ORDERTYPE_AUTO);
            Decidedzone decidedzone = decideZoneDao.findById(decidedZoneID);
            Staff staff = decidedzone.getStaff();
            //分配一个该定区的取派员
            noticebill.setStaff(staff);

            //保存通知单
            noticeBillDao.save(noticebill);

            //产生一个工单
            Workbill workbill = new Workbill();
            workbill.setAttachbilltimes(0);
            workbill.setBuildtime(new Timestamp(System.currentTimeMillis()));
            //设置通知单，关系由workbill来维护
            workbill.setNoticebill(noticebill);
            //设置取件状态
            workbill.setPickstate(Workbill.PICKSTATE_NO);
            //分配该工单的员工
            workbill.setStaff(staff);
            //设置备注信息
            workbill.setRemark(noticebill.getRemark());
            //设置工单类型
            workbill.setType(Workbill.TYPE_1);

            //保存workbill
            workBillDao.save(workbill);

            //发送短信给取派员

        }else {
            //未查询到定区id手动分单
            noticebill.setOrdertype(Noticebill.ORDERTYPE_MAN);
        }

        noticeBillDao.save(noticebill);

    }
}
